package com.cn.dim.controller;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cn.dim.pojo.User;
import com.cn.dim.service.LoginService;
import com.cn.dim.utils.Md5Util;
import com.cn.dim.utils.Md5utils;

@Controller
@RequestMapping("/login")
public class LoginController {

	@Resource
	private LoginService loginService;

	@RequestMapping(value ="/login",method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> login(HttpServletRequest request,User user) throws NoSuchAlgorithmException, UnsupportedEncodingException{
		Map<String,Object> param=new HashMap<>();
		Map<String,Object> reMap=new HashMap<>();
		param.put("username", user.getUsername());
		User u =loginService.getUserByLogin(param);
		String message="";
		String status="success";
		if(u==null){
			message="用户名不存在!";
			status="error";
		}else if(u.getIsdel().equals("1")){
			message="用户已注销";
			status="error";
		}
		else if(u.getIsused().equals("1")){
			message="用户已经被封停";
			status="error";
		}else{
//			String md5password=Md5Util.getEncryptedPwd(user.getPassword());
			if(!Md5Util.validPassword(user.getPassword(),u.getPassword())){
				status="error";
				message="密码错误!";
			}else{
				status="success";
				message="登录成功!";
				HttpSession session = request.getSession(); 
				session.setAttribute("user", u); 
				session.setMaxInactiveInterval(30*60);//以秒为单位
			}
		}
		reMap.put("message", message);
		reMap.put("status", status);
		return reMap;
	}

}
